import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Create by chenhd on 2021/8/28.
 * 方法六：使用信号量Semaphore
 */
public class ConcurrentTask6 {
    public String str;
    public Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) throws InterruptedException {
        ConcurrentTask6 concurrentTask = new ConcurrentTask6();

        concurrentTask.semaphore.acquire();
        new Thread(concurrentTask::putStr).start();

        concurrentTask.semaphore.acquire();
        System.out.println(concurrentTask.getStr());

        concurrentTask.semaphore.release();
    }

    public void putStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
            this.str = "hello concurrent.";
            semaphore.release();
        } catch (InterruptedException e) {
            //log error
            e.printStackTrace();
        }
    }

    public String getStr() {
        return str;
    }
}
